<template>
  <div class="dayjs-example">
    <h2>Day.js 使用示例</h2>
    
    <div class="example-section">
      <h3>当前时间</h3>
      <p>完整格式: {{ currentDateTime }}</p>
      <p>日期格式: {{ currentDate }}</p>
      <p>时间格式: {{ currentTime }}</p>
    </div>
    
    <div class="example-section">
      <h3>相对时间</h3>
      <p>相对于现在: {{ relativeTime }}</p>
    </div>
    
    <div class="example-section">
      <h3>日期计算</h3>
      <p>7天后: {{ nextWeek }}</p>
      <p>30天前: {{ lastMonth }}</p>
    </div>
    
    <div class="example-section">
      <h3>自定义日期</h3>
      <input v-model="customDate" type="date" />
      <p>格式化结果: {{ formattedCustomDate }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import relativeTimePlugin from 'dayjs/plugin/relativeTime';

// 设置dayjs插件和本地化
dayjs.extend(relativeTimePlugin);
dayjs.locale('zh-cn');

// 响应式数据
const now = ref(dayjs());
const customDate = ref('');

// 定时器ID，用于清除定时器
let timer: NodeJS.Timeout | null = null;

// 计算属性
const currentDateTime = computed(() => now.value.format('YYYY-MM-DD HH:mm:ss'));
const currentDate = computed(() => now.value.format('YYYY-MM-DD'));
const currentTime = computed(() => now.value.format('HH:mm:ss'));
const relativeTime = computed(() => now.value.fromNow());
const nextWeek = computed(() => now.value.add(7, 'day').format('YYYY-MM-DD'));
const lastMonth = computed(() => now.value.subtract(30, 'day').format('YYYY-MM-DD'));
const formattedCustomDate = computed(() => {
  return customDate.value ? dayjs(customDate.value).format('YYYY年MM月DD日 dddd') : '';
});

// 生命周期
onMounted(() => {
  // 每秒更新一次时间
  timer = setInterval(() => {
    now.value = dayjs();
  }, 1000);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
</script>

<style scoped>
.dayjs-example {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.example-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.example-section h3 {
  margin-top: 0;
  color: #333;
}

input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>